<!-- 座席报表 -->
<template>
  <div class="report_main">
      <tabs :tabPane="tabPaneList" v-model="activeName" @tab-click='toSerach(false)' />
      <continer class="webchatContainer">
        <template slot="search">
          <quickSearch v-if="flag" :advForm="quickSearchForm" @QuickSearch="headerQuery">

          </quickSearch>
          <quickSearch v-else :advForm="quickSearchForm2" @QuickSearch="headerQuery">

          </quickSearch>
        </template>
        <template slot="oprate">
          <el-button type="primary" size="mini" @click="toSerach(false)">查询</el-button>
          <el-button  size="mini" @click="toSerach(false)">刷新</el-button>
        </template>
        <template slot="content">
          <p class="overviewOfConversation">趋势</p>
          <div id="timeTrend"  />
          <p class="overviewOfConversation lh30">
          <span class="xiangqing" style="margin-right: 6px">详情</span>
          <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42  myIcon" style='color: #E0E6F0' v-popover:explainPopover></span>
          <!-- <el-button @click="jisuan(tableData, formulaList)">测试</el-button> -->
          <span class="floatRight" style="cursor: pointer;">
            <span class="slider">
              <span :class="timeState === 'second' ? 'selected':''" @click="timeStateChange('second')">秒</span>
              <span :class="timeState !== 'second' ? 'selected':''" @click="timeStateChange('HMS')">时分秒</span>
            </span>
            <!-- 表头设置 -->
            <el-dropdown trigger="click" @visible-change="headerChange">
              <span class="el-dropdown-link">
                <i title="自定义表头" class="V7_iconfont V7_iconV7tubiao_zidingyi fz14" :class="isClick? 'icon-active': ''"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <searchCheckBox
                  :data="realHeader"
                  @check-change="handleCheckChange"
                ></searchCheckBox>
              </el-dropdown-menu>
            </el-dropdown>
            <!-- 自定义公式 -->
            <i title="自定义公式" @click="showDrawer" style="margin-left: 20px" class="V7_iconfont V7_iconV7tubiao_gongshi fz14"></i>
            <!-- 导出 -->
            <el-popover

              placement="top"
              width="100"
              trigger="click"
              popper-class="custom-search-pop"
              >
              <p style="margin-top: 6px" class='exportReport' @click="exportReport('part')">导出当前表格</p>
              <p style="margin-bottom: 6px" class='exportReport' @click="exportReport('all')">导出详细信息</p>
              <i  slot="reference" title="导出" style="margin-left: 20px" class="V7_iconfont V7_iconV7tubiao_daochu fz14"></i>
            </el-popover>
            <!-- <el-button @click="loading=true">测试</el-button> -->

          </span>
        </p>
        <uTable style="min-height:150px" v-loading='tableLoading' :key="tableKey"  :tableHeaders='actualHeader' :tableData="tableData"></uTable>
        </template>
      </continer>
       <CustomFormula ref='Custom' :nowHeader="nowHeader" :formulaType="activeName" :show.sync='toshow' :formulaList='formulaList' @getCustomFormula='getCustomFormula' @saveCustomFormula='saveCustomFormula' @cancelFun='cancelFun'> </CustomFormula>
        <el-popover
          ref="explainPopover"
          placement="top"
          width="500"
          trigger="hover"
          popper-class="custom-search-pop"
          >
         <div class='explainMain'>
           <p v-for="item in nowHeader.filter(i => i.notes)" :key="item.label"><span style="color:#303753">{{item.label}}: </span><span style="color:#686E84">{{item.notes}}</span></p>
         </div>
        </el-popover>
  </div>
</template>

<script lang='ts'>
import { Component, Vue } from 'vue-property-decorator'
import tabs from '@/components/configCommon/configTabs.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import quickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import customSearch from '@/views/dataCenter/callData/customSearch.vue'
import searchCheckBox from '@/components/configCommon/operate-modules/SearchCheckbox/index.vue'
import { uTable, CheckBox, CheckBoxItem, OtherSelect, Loading, CustomFormula } from './components/index'
import { commonAction, deepClone, getFormatDateTime, isHasFuncOrMenus } from '@/utils/common'
import { ExportExcel } from '../../../../public/static/js/worker' // 导出
import * as formula from './base/formulaUtil' // 自定义公式相关
import { drawCharts, timeTrend, qualityCharts } from './base/echart'
import { selfTimeSetting } from './base/timeSetting'
import { agentWorkloadHeader, agentWorkQualityHeader } from './base/tableHeader/agentHeader'
import { tableHeaders } from './base/tableHeader/header'
import { WebchatModule } from '@/store/modules/webchat'

const method = 'post'

@Component({
  name: 'AgentReport',
  components: { CustomFormula, tabs, continer, quickSearch, searchCheckBox, uTable, customSearch }
})
export default class AgentReport extends Vue {
  private $store
  private activeName = 'agentWork'
  private tabPaneList = [
    {
      label: '座席工作量报表',
      name: 'agentWork',
      _id: 'im_agent_report'
    },
    {
      label: '座席工作质量报表',
      name: 'agentWorkQuality',
      _id: 'im_agent_quality_report'
    }
  ]

  private permissionControl () { // tab权限控制
    const arr = ['im_agent_report', 'im_agent_quality_report']
    const newArr: any[] = []
    arr.forEach((item: string) => {
      if (isHasFuncOrMenus(item, this.$store.state.common.session.user, true)) {
        newArr.push(item)
      }
    })
    this.tabPaneList = this.tabPaneList.filter(item => newArr.indexOf(item._id) > -1)
    this.activeName = this.tabPaneList[0] ? this.tabPaneList[0].name : 'agentWork'
  }

  get flag () {
    return this.activeName === 'agentWork'
  }

  get nowHeader () {
    return this.activeName === 'agentWork' ? agentWorkloadHeader : agentWorkQualityHeader
  }

  private quickSearchForm: any = {
    // 快捷检索数据（时间条件，类型）
    form: {
      createTime: [
        // 创建时间 默认显示最近七天
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0] + ' 00:00:00',
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0] + ' 23:59:59'
      ],
      agentList: [] // 座席列表
    },
    advSearchOptions: [], // 初始查询项
    selfPickerOptions: selfTimeSetting
  }

  private quickSearchForm2: any = {
    // 快捷检索数据（时间条件，类型）
    form: {
      createTime: [
        // 创建时间 默认显示最近七天
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0] + ' 00:00:00',
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 1), '').split(' ')[0] + ' 23:59:59'
      ],
      agentList: [] // 座席列表
    },
    advSearchOptions: [],
    selfPickerOptions: selfTimeSetting
  }

  private async toSerach (active) {
    setTimeout(() => {
      this.headerQuery(active)
      this.dataQuery()
    }, 300);
  }

  get userList () {
    const list = deepClone(this.$store.state.common.publicCache.userList)
    for (const i of list) {
      i.display = i.agentNumber + ' ' + i.agentName
    }
    return list
  }

  private webchatStatusList: any = []
  private webchatStatusMap = new Map()
  private async getWebchatStatusList () {
    await WebchatModule.webchatCommonAction({ url: '/im-center/action/user/status/cache', method: 'POST' }).then((statuts: any) => { // 在线自定义状态
      if (statuts && statuts.data) {
        this.webchatStatusList = []
        const map = new Map()
        for (const item of statuts.data) {
          map.set(item._id, item)
          this.webchatStatusList.push({
            label: item.name + '总时长',
            prop: item._id,
            width: 120,
            HMS: true
          })
        }
        this.webchatStatusMap = map
      }
    })
  }

  get map () {
    // const map = new Map()
    // for (const item of this.$store.state.common.publicCache.userList) {
    //   map.set(item._id, item)
    // }
    return this.$store.state.common.publicCache.userListObj
  }

  private headerChange (val) { // 表头修改
    if (!val) {
      const url = '/im-center/action/report/header/update'
      this.actualHeader.forEach(element => {
        if (element.prop.includes('-')) {
          element.isCustomHeader = true
        } else {
          element.isCustomHeader = false
        }
      });
      const data = { type: this.activeName, config: this.actualHeader }
      commonAction({ url, method: 'post', data }).then(res => {
        this.headerQuery()
      })
    }
  }

  private async mounted () {
    this.permissionControl()
    await this.getWebchatStatusList()
    this.getSatisfactionList()
    await this.headerQuery()
    this.dataQuery()
    this.quickSearchForm.advSearchOptions = [
      // 快捷检索的数据
      {
        label: '时间',
        inputType: 'dateTimeRange',
        clearable: false,
        name: 'createTime'
      },
      { label: '座席', inputType: 'select', selectData: this.userList, name: 'agentList', filterable: true, multiple: true, clearable: true, defaultProp: { label: 'display', value: '_id' } }
    ]
    this.quickSearchForm2.advSearchOptions = [
      // 快捷检索的数据
      {
        label: '时间',
        inputType: 'dateTimeRange',
        clearable: false,
        name: 'createTime'
      },
      { label: '座席', inputType: 'select', selectData: this.userList, name: 'agentList', filterable: true, multiple: true, clearable: true, defaultProp: { label: 'display', value: '_id' } }
    ]
  }

  private dataQuery () {
    const url = this.flag ? '/im-report/agent/workload/queryData' : '/im-report/agent/quality/queryData'
    const data = this.flag ? this.quickSearchForm.form : this.quickSearchForm2.form
    commonAction({ url, method, data }).then(res => {
      if (!this.flag) {
        this.tableData = res.data.basicData || []
        const list = this.getSatisfactionHeader(this.satisfactionList)
        for (let i = 0; i < list.length; i++) {
          const e = list[i].prop
          this.tableData.forEach(q => {
            q[e] = 0
            q[e + 'val'] = 0
          })
        }
        for (let i = 0; i < res.data.csrList.length; i++) {
          const element = res.data.csrList[i];
          const val = this.tableData.find(m => m.agentId === element.agent) || {}
          val[element.satisfactionKey] = element.satisfactionKeyRate
          val[element.satisfactionKey + 'val'] = element.satisfactionKeyCount
        }
      } else {
        this.tableData = res.data.basicData || []
        const list0 = res.data.agentStatus?.filter(item => item.type === 'login') || []
        const list = list0.map(i => i.agentId) || []
        const list2 = this.tableData.map(i => i.agentId)
        const list3: any = []
        list.forEach(element => {
          if (!list2.includes(element)) {
            list3.push(element)
          }
        })
        for (let k = 0; k < list3.length; k++) {
          const e = list3[k];
          const obj: any = {}
          if (this.tableData[0]) {
            Object.keys(this.tableData[0]).forEach(item => {
              if (item === 'agentId') {
                obj[item] = e
              } else {
                obj[item] = 0
              }
            })
          } else {
            agentWorkloadHeader.concat(
              {
                label: '座席姓名',
                prop: 'agentId',
                width: 120,
                show: true,
                notes: '座席姓名',
                fixed: 'left',
                isCustomHeader: false
              }
            ).forEach(q => {
              if (q.prop === 'agentId') {
                obj[q.prop] = e
              } else {
                obj[q.prop] = 0
              }
            })
          }

          this.tableData.push(obj)
        }
        list0.forEach(val => {
          const item = this.tableData.find(i => i.agentId === val.agentId) || {}
          item.loginTotalTimeLength = val.timeLength
        })
        this.webchatStatusList.forEach(k => {
          this.tableData.forEach(j => {
            j[k.prop] = 0
          })
        })
        for (let q = 0; q < res.data.agentStatus.length; q++) {
          const element = res.data.agentStatus[q]
          const val = this.tableData.find(m => m.agentId === element.agentId) || {}
          val[element.type] = element.timeLength
        }
      }
      setTimeout(() => {
        let realdata
        const f = this.tableData.find(i => i.flag === '总计')
        if (f) {
          realdata = this.tableData
        } else {
          realdata = this.tableData.concat(this.getTotal(res.data.basicData))
        }
        formula.jisuan(deepClone(realdata), this.formulaList).then((val: any) => {
          if (!this.tableData.length) {
            val = []
          }
          // (val, 112233)
          this.$set(this, 'tableData', val)
          this.tableKey++
          this.tableLoading = false
          this.timeStateChange('HMS')
        })
      }, 600)

      this.chartInit()
    })
  }

  private async headerQuery (active?: boolean) { // 表头查询
    function unique (val, char = 'prop') { // 对象数组去重
      const list = new Map()
      return val.filter(item => !list.has(item[char]) && list.set(item[char], 1))
    }
    const url = '/im-center/action/report/header/query'
    const data = { type: this.activeName }
    const otherHeader = !this.flag ? this.getSatisfactionHeader(this.satisfactionList) : this.webchatStatusList
    // (otherHeader, 1122)
    await commonAction({ url, method, data }).then(res => {
      if (res.success) {
        const list = res.data?.config
        for (const element of otherHeader) {
          const index = list.findIndex(i => i.prop === element.prop)
          const real = list[index]
          if (!real) {
            list.push(element)
          } else {
            real.label = element.label
          }
          if (!this.flag) {
            if (!element.isUse) {
              list.splice(index, 1)
            }
          }
        }
        this.getCustomFormula(list, active)
      }
    })
  }

  private list = [
    { name: '接待会话总数', code: 'initCount' },
    { name: '分配会话数', code: 'assignCount' },
    { name: '有效会话数', code: 'invalidCount' },
    { name: '主动会话数', code: 'inviteCount' },
    { name: '处理留言数', code: 'delLeavingCount' }
  ]

  private chartInit () {
    const data: any = this.flag ? deepClone(timeTrend) : deepClone(qualityCharts)
    for (let m = 0; m < this.tableData.length; m++) {
      const e: any = this.tableData[m]
      if (e.flag === '总计') {
        continue
      }
      data.xAxis.data.push(this.map[e.agentId]?.agentName + `(${this.map[e.agentId]?.agentNumber})` || '')
      for (let i = 0; i < data.series.length; i++) {
        const element = data.series[i]
        element.data.push(e[element.code])
      }
    }
    if (this.tableData.length > 8) {
      data.xAxis.axisLabel = {
        rotate: 15,
        interval: 0
      }
      if (this.tableData.length > 20) {
        data.xAxis.axisLabel = {
          rotate: 15
        }
      }
    }
    const resizeWidth = document.querySelector('.header-contain')?.scrollWidth || 300
    drawCharts('#timeTrend', data, { width: resizeWidth, height: 300 })
  }

  private headerInit (arr: any = [], flag = true) {
    const item = arr.find(i => i.prop === 'agentId') || {}
    item.disenable = true
    item.fixed = 'left'
    if (item) {
      item.formatter = (row, column, cellValue, index) => {
        if (cellValue === '总计') {
          return '总计'
        }
        return this.map[cellValue]?.agentName + `(${this.map[cellValue]?.agentNumber || ''})`
      }
    }
    if (flag) {
      this.$set(this, 'realHeader', arr)
    }
    this.$set(this, 'actualHeader', arr)
  }

  private otherHeaders = []
  private actualHeader: any = []
  private tableData: any = []
  private tableLoading = false

  private toshow = false
  private formulaList: any = []
  private showDrawer () {
    this.toshow = true
    this.getCustomFormula()
  }

  private customFormulaHeader: any = []
  private getCustomFormula (list?: any, flag?: any) {
    list = list || deepClone(this.actualHeader)
    const otherHeader = !this.flag ? this.getSatisfactionHeader(this.satisfactionList) : this.webchatStatusList
    const url = '/im-report/formula/getList'
    const data = { formulaType: this.activeName }
    commonAction({ url, method: 'post', data }).then(res => {
      if (res.success) {
        this.$set(this, 'formulaList', res.data)
        this.getCustomFormulaHeader(this.formulaList)
        const myHeader = this.customFormulaHeader.concat(otherHeader)
        for (let i = 0; i < list.length; i++) {
          const element = list[i]
          if (element.isCustomHeader) {
            if (!myHeader.find(item => item.prop === element.prop)) {
              list.splice(i, 1)
              i--
            }
          }
        }
        this.customFormulaHeader.forEach(element => {
          if (!list.find(item => item.prop === element.prop)) {
            list.push(element)
          } else {
            const val = list.find(item => item.prop === element.prop)
            val.label = element.label
          }
        })
        this.headerInit(list)
        if (flag) {
          setTimeout(() => {
            let realdata
            const f = this.tableData.find(i => i.flag === '总计')
            if (f) {
              realdata = this.tableData
            } else {
              realdata = this.tableData.concat(this.getTotal(res.data.basicData))
            }

            formula.jisuan(realdata, this.formulaList).then((val: any) => {
              if (!this.tableData.length) {
                val = []
              }
              console.log(realdata, this.formulaList, val)
              this.$set(this, 'tableData', val)
              this.tableKey++
              this.tableLoading = false
              this.timeStateChange('HMS')
            })
          }, 600)
        }
      }
    })
  }

  private getCustomFormulaHeader (arr: any[]) {
    const list: any = []
    arr.forEach(item => {
      let flag = false
      for (const key in item.variables) {
        if (item.variables[key].includes('Len')) {
          flag = true
        }
      }
      list.push({
        label: item.formulaName,
        prop: item._id,
        width: 120,
        show: true,
        isCustomHeader: true,
        formulaStr: item.formulaStr,
        variables: item.variables,
        digits: item.digits,
        HMS: flag
      })
    })
    this.customFormulaHeader = list
  }

  private getSatisfactionHeader (arr) {
    const list: any = []
    arr.forEach(element => {
      list.push({
        label: element.name + '比例',
        prop: element.key,
        show: true,
        type: 'percentage',
        noCalculation: true,
        isUse: element.isUse
      })
    })
    return list
  }

  private saveCustomFormula (data, flag) {
    const url = '/im-report/formula/addUpdate'
    commonAction({ url, method, data }).then(res => {
      if (res.success) {
        (this as any).$message.success(flag ? '添加成功' : '修改成功');
        (this.$refs.Custom as any).reset()
        this.toshow = false
        this.getCustomFormula(false, true)
      }
    })
  }

  private cancelFun () {
    (this.$refs.Custom as any).reset()
    this.getCustomFormula(false, true)
    // (233334)
  }

  private total = {}
  private getTotal (arr) { // 求合计
    // const {review} = require('./base/timeConversion')
    // // (review)
    arr = this.tableData
    const total: any = {}
    const obj = this.tableData[0] || {}
    Object.keys(obj).forEach(item => {
      total[item] = 0
    })
    for (let i = 0; i < arr.length; i++) {
      const element = arr[i]
      for (const key in total) {
        if (isNaN(element[key])) {
          if (isNaN(total[key])) {
            total[key] = 0
          }
        } else {
          total[key] += Number(element[key])
        }
      }
    }

    const nowHeader = this.flag ? agentWorkloadHeader.concat(this.webchatStatusList) : agentWorkQualityHeader
    const list = nowHeader.concat(this.getSatisfactionHeader(this.satisfactionList)).filter(item => item.type === 'percentage').map(i => i)
    list.forEach(e => {
      if (e.noCalculation) {

        // total[e.prop] = '--'
      } else {
        // total[e.prop] = ((total[e.prop] / arr.length)).toFixed(2) + '%'
      }
    })
    if (!this.flag) {
      total.twentyFourHourSolutionRate = this.getNumber((total.initCount - total.twentyFourHourRepeatCount) / total.initCount, true)
      total.fortyEightHourSolutionRate = this.getNumber((total.initCount - total.fortyEightHourRepeatCount) / total.initCount, true)
      total.pushCsrRate = this.getNumber(total.pushCsrCount / total.initCount, true)
      total.evaluateRate = this.getNumber(total.evaluateCount / total.initCount, true)
      total.quesAndAnswerRate = this.getNumber(total.agentSendMsgCount / total.visitorSendMsgCount, true)
      total.avgFirstResponseNotIncludeLen = this.getNumber(total.firstResponseNotIncludeLen / total.firstResponseNotIncludeCount)
      // (total.firstResponseNotIncludeCount, total.firstResponseNotIncludeCount)
      total.avgSessionNotIncludeTimeLen = this.getNumber(total.sessionNotIncludeTimeLen / total.assignCount)
      total.avgMsgResponseLen = this.getNumber(total.msgResponseLen / total.msgResponseCount)
      this.satisfactionList.forEach(i => {
        if (i.isUse) {
          console.log(total[i.key + 'val'], total.evaluateCount)
          total[i.key] = this.getNumber(total[i.key + 'val'] / total.evaluateCount, true)
        }
      })
    }
    total.agentId = '总计'
    total.flag = '总计'
    this.total = total
    return total
  }

  private handleCheckChange (arr, flag) {
    if (arr.length) {
      this.headerInit(arr, false)
    }
    // // (arr)
  }

  private getNumber (val, flag?: boolean) {
    if (isNaN(Number(val))) {
      return '--'
    } else if (flag) {
      return Number(val * 100).toFixed(2)
    } else {
      return Number(val).toFixed(2)
    }
  }

  private realHeader = []
  // get realHeader () {
  //   return deepClone(this.actualHeader)
  // }
  private satisfactionList: any = []
  private async getSatisfactionList () {
    const actionData = { url: '/im-center/action/config/satisfaction/list', method, data: {} }
    await commonAction(actionData).then(res => {
      if (res.success) {
        this.satisfactionList = res.data.list[0].radioTagText
      }
    })
  }

  private exportReport (val) {
    const header = deepClone(this.actualHeader)
    const tableData = deepClone(this.tableData)
    const year = new Date().getFullYear() + ''
    const month = new Date().getMonth() + 1 + ''
    const day = new Date().getDay() + ''
    const time = `${year}${month}${day}`
    const name = `${time}-${this.$store.state.common.session.user.agentName || ''}-会话报表`
    delete header[0].formatter
    for (const i of tableData) {
      if (i.agentId !== '总计') {
        i.agentId = this.map[i.agentId]?.agentName + `(${this.map[i.agentId]?.agentNumber || ''})`
      }
    }
    if (val === 'all') {
      const de = new ExportExcel(header, tableData)
      de.toExport(name)
    } else {
      const de = new ExportExcel(header.filter(item => item.show), tableData)
      de.toExport(name)
    }
  }

  // timeConversion
  private tableKey = 0
  private isClick = false
  private timeState = 'second' // 时分秒: HMS

  private timeStateChange (val, data?: any) {
    data = data || this.tableData
    const nowHeader = this.flag ? agentWorkloadHeader.concat(this.webchatStatusList) : agentWorkQualityHeader.concat(this.getSatisfactionHeader(this.satisfactionList))
    const list1 = this.customFormulaHeader.concat(nowHeader).filter(item => item.HMS)
      .map(i => i.prop)
    const list2 = this.customFormulaHeader.concat(nowHeader).filter(item => item.type === 'percentage').map(i => i.prop)
    const timeTransformation = require('./base/timeConversion')
    this.timeState = val
    const db = val === 'second' ? timeTransformation.formatHSM : timeTransformation.formatSeconds
    data.forEach(element => {
      list1.forEach(r => {
        element[r] = db(element[r])
      })
      list2.forEach(s => {
        element[s] = getval(element[s])
      })
    });
    this.tableKey++

    function getval (v) {
      if (v === '--') {
        return '--'
      }
      if ((v + '').includes('%')) {
        return v
      }
      if (isNaN(Number(v))) {
        return '0%'
      } else {
        if ((v + '').includes('.')) {
          return Number(v).toFixed(2) + '%'
        } else {
          return v + '.00%'
        }
      }
    }
  }
}

</script>
<style lang='stylus' scoped>
@import './css/index.styl'

</style>
<style lang='stylus'>
.custom-search-pop
  padding 0
  min-width unset
.report_main .handle-wrapper
  padding-bottom 20px
.reportTable:last-child
  font-weight: 600
  color #686E84
  *[title='总计']
      font-family: PingFang SC;
      color: #008BEE;
.explainMain
  padding 14px
  height 210px
  overflow auto
</style>
